package vip.youngboy.freejump.handler.event;

import org.activiti.engine.TaskService;
import org.activiti.engine.delegate.event.ActivitiEntityEvent;
import org.activiti.engine.delegate.event.ActivitiEventType;
import org.activiti.engine.impl.persistence.entity.TaskEntity;
import org.springframework.beans.factory.annotation.Autowired;
import vip.youngboy.freejump.domain.process.TaskOpinion;
import vip.youngboy.freejump.domain.process.UserOptions;
import vip.youngboy.freejump.parse.user.UserSettingParser;
import vip.youngboy.freejump.repository.TaskOpinionRepository;

import java.util.Set;

public class TaskCreateEventHandler extends AbstractTaskEventHandler {

    @Autowired
    protected TaskOpinionRepository taskOpinionRepository;

    @Autowired
    protected UserSettingParser userSettingParser;

    @Autowired
    protected TaskService taskService;

    @Override
    public void handleTaskEvent(ActivitiEntityEvent event) {
        //持久化流程执行堆栈记录和历史审批记录
        TaskEntity entity = (TaskEntity) event.getEntity();
        String taskId = entity.getId();
        //从流程定义中获取人员规则配置信息
        UserOptions userOptions = null;
        //解析当前任务的人员配置，并计算对应的人员
        Set<String> candidateUsers = userSettingParser.parseUserOptions(userOptions);
        if (candidateUsers.isEmpty()) {
            //可以考虑跳过此任务

        } else if (candidateUsers.size() == 1) {
            //设置assign
            taskService.setAssignee(taskId, candidateUsers.iterator().next());
        } else {
            //设置候选人

        }
        recordTaskOpinion(entity);
    }

    /**
     * 保存任务开始流转记录
     */
    protected void recordTaskOpinion(TaskEntity entity) {
        TaskOpinion startTaskOpinion = TaskOpinion.createStartTaskOpinion(entity);
        taskOpinionRepository.save(startTaskOpinion);
    }

    @Override
    public ActivitiEventType supportType() {
        return ActivitiEventType.TASK_CREATED;
    }
}
